import BaseController from '../../core/controllers/Base.controller';

@Inject('$log', '$rootScope', '$scope', '$state', 'globalService', 'deviceService', 'ngDialogService')
class EditDeviceInfoController extends BaseController {
  constructor() {
    super();

    this.view = {
      avatarFile: null,
      attachmentFiles: [],
    };

    const deviceId = $state.params.id;
    $scope.$watch('vm.selectedWorkers', (newVal) => {
      $log.info(newVal);
    }, true);
    this.$detailQuery(deviceId);
    this.selectedWorkers = [];
  }

  $detailQuery(deviceId) {
    this.deviceService
      .get(deviceId)
      .then((res) => {
        this.deviceDetailInfo = res.data;
        this.$handleOperator(this.deviceDetailInfo);
        this.view.avatarFile = this.deviceDetailInfo.imageId;
        this.view.attachmentFiles = this.deviceDetailInfo.files;
        this.view.attachmentFiles.forEach((item) => {
          item.name = item.fileName;
        });
      });
  }

  /*eslint-disable */
  $handleOperator(params) {
    this.obj = {};
    if (params.operatorNames && params.operatorIds && params.operatorIds.length > 0) {
      const result = params.operatorNames.split(',');
      for (let i = 0; i < params.operatorIds.length; i++) {
        this.obj = {
          id: params.operatorIds[i],
          fullName: result[i],
        }
        this.selectedWorkers.push(this.obj);
      }
    }
  }

  // 获得头像src
  $getAvatarSrc() {
    if (this.deviceDetailInfo && this.deviceDetailInfo.image &&
      this.deviceDetailInfo.image.filePath) {
      const src = `/${this.deviceDetailInfo.image.filePath}`;
      return src;
    } else {
      return require('../../assets/images/' + 'addBt.jpg');
    }
  }

  $saveData(param) {
    this.deviceDetailInfo.operatorIds = [];
    this.selectedWorkers.forEach((item) => {
      this.deviceDetailInfo.operatorIds.push(item.id);
    })
    this.deviceDetailInfo.attachmentIds = this.view.attachmentFiles.map(item => item.id);
    if (this.view.avatarFile && this.view.avatarFile.id) {
      this.deviceDetailInfo.imageId = this.view.avatarFile.id;
    }
    this.deviceService
      .update(this.deviceDetailInfo)
      .then((res) => {
        this.$log.debug(res);
        if (res.success) {
          this.$state.go('deviceInfoDetail', { id: res.data.id });
          this.ngDialogService.alertSuccess(res.message);
        } else {
          this.ngDialogService.alertError(res.message);
        }
      });
  }
}

export default EditDeviceInfoController;
